package org.ring.config.server;

import org.ring.common.transport.Connection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @since 2024-08-06 19:19
 */
public class SubscribeRelation<T> {

    /**
     * topic -> connection collection
     */

    private final Map<T,List<Connection>> topicToConn = new ConcurrentHashMap<>();
    //connectionId ,

    public void add(T topic, Subscriber subscriber) {
        List<Connection> s = topicToConn.computeIfAbsent(topic, (k) -> new ArrayList<>());
        s.add(subscriber.getConnection());
        //lock

        Set<T> topics = (Set<T>) subscriber.getConnection().attachment();
        if (topics == null) {
            topics = new HashSet<>();
            subscriber.getConnection().attachment(topics);
        }
        topics.add(topic);
    }

    public Collection<Connection> getSubscribers(T topic){
        return topicToConn.get(topic);
    }

    public void remove(Connection connection){
        Set<Object> topics = (Set<Object>) connection.attachment();
        if(topics == null){
            return;
        }
        for(Object topic : topics){
            Collection<Connection> conns = topicToConn.get(topic);
            conns.remove(connection);
        }
    }



}
